package com.jxstjh.conch.handler.shield.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jxstjh.conch.common.domain.AnchorInfo;
import com.jxstjh.conch.common.domain.TaskInfo;
import com.jxstjh.conch.common.enums.AnchorStateEnum;
import com.jxstjh.conch.common.enums.ShieldTypeEnum;
import com.jxstjh.conch.handler.shield.ShieldService;
import com.jxstjh.conch.support.utils.LogUtil;
import com.jxstjh.conch.support.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;

@Service
@Slf4j
public class ShieldServiceImpl implements ShieldService {

    private static final String NIGHT_SHIELD_BUT_NEXT_DAY_SEND_KEY = "night_shield_send";

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LogUtil logUtil;

    @Override
    public void shield(TaskInfo taskInfo) {

        /**
         * 当消息下发至消息中心时已经是凌晨, 业务希望此类消息在次日的早上X点推送
         * 此功能要配合分布式定时任务搞定(Xxl-Job)
         */
        if (isNight()) {
            if (ShieldTypeEnum.NIGHT_SHIELD.getCode().equals(taskInfo.getShieldType())) {
                logUtil.print(AnchorInfo.builder().state(AnchorStateEnum.NIGHT_SHIELD.getCode())
                        .businessId(taskInfo.getBusinessId()).ids(taskInfo.getReceiver()).build());
            }
            if (ShieldTypeEnum.NIGHT_SHIELD_BUT_NEXT_DAY_SEND.getCode().equals(taskInfo.getShieldType())) {
                redisUtil.lPush(NIGHT_SHIELD_BUT_NEXT_DAY_SEND_KEY, JSON.toJSONString(taskInfo,
                        new SerializerFeature[]{SerializerFeature.WriteClassName}),
                        (DateUtil.offsetDay(new Date(), 1).getTime() / 1000) - DateUtil.currentSeconds());
                logUtil.print(AnchorInfo.builder().state(AnchorStateEnum.NIGHT_SHIELD_NEXT_SEND.getCode()).businessId(taskInfo.getBusinessId()).ids(taskInfo.getReceiver()).build());
            }
            taskInfo.setReceiver(new HashSet<>());
        }
    }

    /**
     * 目前认为最早的消息发送时间是早上9点, 所以小时数 < 8都默认是凌晨(即夜晚)
     *
     * @return
     */
    private Boolean isNight() {
        return Integer.valueOf(DateFormatUtils.format(new Date(), "HH")) < 8;
    }
}
